<template>
  <el-card class="app-container">
    <div>
      <div class="itemTitle">隐患上报</div>
      <div class="search">
        <el-form :inline="true" :model="queryParams" ref="queryForm">
          <el-col :span="5">
            <el-form-item label="隐患名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入隐患名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item>
              <el-button type="primary" @click="handleQuery">搜索</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </div>
      <div class="content">
        <div class="ct-table-only">
          <elTables :table-data="tableData" :columns="tableColumns" :totalLength="total" :currentPage="queryParams.pageNum"
            :handle-current-change="handleCurrentChange" isPagin :curHeight="tableHeight" />
        </div>
      </div>
    </div>
    <el-dialog title="隐患台账详情" :visible.sync="open" append-to-body @close="cancel" class="dialog-form">
      <SubmitHistoryForm :info="info" :row="row" :imgs="imgLists"></SubmitHistoryForm>   
    </el-dialog>
  </el-card>
</template>

<script>
const defaultQueryParams = {
  pageNum: 1,
  pageSize: 10,
};
import { pageDanger,getDanger, delDanger, addDanger, updateDanger, pageDangerRecord } from "@/api/risk/danger";
import { listRoom, listShop } from "@/api/video/monitor";
import SubmitHistoryForm from "./components/submitHistoryForm.vue";
export default {
    name: "Danger",
    components:{ SubmitHistoryForm },
    data() {
        return {
            open:false,
            tableHeight: 0,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            tableData: [],
            // 查询参数
            queryParams: {
                ...defaultQueryParams,
                name: null,
                factoryId: null,
            },
            statusOptions: {
                '1': '已上报',
                '2': '已确认',
                '3': '已整改',
                '4': '已验收'
            },
            tableColumns: [
                { key: "name", title: "隐患名称" },
                { key: "desc", title: "隐患描述" },
                { key: "shopName", title: "车间" },
                { key: "shopRoomName", title: "工房" },
                { key: "createTime", title: "创建时间" },
                { key: "createName", title: "创建人" },
                { key: "status", title: "隐患状态", render: (h, params) => {
                  return h("div", [
                    h("el-tag", {
                      props: {
                          type: "success"
                      },
                    },
                    this.statusOptions[params.row.status]),
                  ]);
                }},
                {
                    title: "操作",
                    align: "center",
                    fixed: 'right',
                    width: 80,
                    render: (h, params) => {
                        return h("div", [
                            h("el-button", {
                                props: {
                                    type: "text",
                                    size: "small",
                                },
                                directives: [
                                    {
                                        name: "hasPermi",
                                        value: ["risk:danger:info"],
                                    },
                                ],
                                on: {
                                    click: () => {
                                        this.handleUpdate(params.row, 2);
                                    },
                                },
                            }, "查看")
                        ]);
                    },
                },
            ],
            listRoom: [],
            listShop: [],
            fileList: [],
            info:{},
            row:{},
            imgLists:[],
        };
    },
    created() {
        this.getPage();
    },
    mounted() {
        this.$nextTick(() => {
            this.getTableHeight();
        });
    },
    methods: {
        handleExceed(files, fileList) {
            this.$message.error(`只允许上传单个文件`);
        },
        // 移除文件
        removeFile(file, fileList) {
            this.fileList = fileList;
        },
        // 上传文件
        success(response, file, fileList) {
            if (response.code == 200) {
                this.fileList = fileList;
                this.$refs.form.clearValidate("imgUrl");
                this.$message.success("上传成功！");
            }
        },
        handleShopChange(val) {
            delete this.form.shopRoomId;
            console.log('change.val', val);
            this.getlistRoom(val);
        },
        //获取工房
        getlistRoom(val) {
            let params = { workShopId: val };
            listRoom(params).then((res) => {
                this.listRoom = res.data;
            });
        },
        //获取车间
        getlistShop() {
            listShop().then((res) => {
                this.listShop = res.data;
            });
        },
        getTableHeight() {
            let height = document.getElementsByClassName('ct-table-only')[0].clientHeight;
            this.tableHeight = height - 40;
        },
        handleCurrentChange(val) {
            this.queryParams.pageNum = val;
            this.getPage();
        },
        /** 查询隐患上报列表 */
        getPage() {
            this.loading = true;
            pageDangerRecord(this.queryParams).then(response => {
                this.tableData = response.data.records;
                this.total = response.data.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
          this.open = false;
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                name: null,
                shopId: null,
                shopRoomId: null,
                desc: null,
                imgUrl: null,
                status: "0",
                isDanger: null,
                level: null,
                rectifyType: null,
                rectifyTime: null,
                rectifyAsk: null,
                factoryId: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                createDept: null,
                delFlag: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getPage();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.isEdit = true;
            this.title = "新增隐患上报";
            this.getlistShop();
        },
        /** 修改按钮操作 */
        handleUpdate(row, type) {
            this.getlistShop();
            this.open=true;
            this.row=row;
            const id = row.id || this.ids;
            getDanger(id).then(response => {
                this.form = response.data;
                this.info = response.data;
                this.imgLists=(JSON.parse(response.data.imgUrl)??[]).map(_ => {
                  return {
                    ..._,
                    url:process.env.VUE_APP_BASE_API+_.url,
                  }
                }); 
                this.getlistRoom(this.form.shopId);
            });
        },
        /** 提交按钮 */
        submitForm() {
            // 对imgUrl处理
            if (this.fileList && this.fileList.length > 0) {
                let ls = this.fileList.map(_ => {
                    return {
                        url: _?.response?.fileName ?? _.url,
                        name: _?.response?.oldFileName ?? _.name,
                    };
                });
                this.form.imgUrl = JSON.stringify(ls);
            }
            else {
                this.form.imgUrl = '';
            }
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        updateDanger(this.form).then(response => {
                            this.fileList = [];
                            this.msgSuccess("修改成功");
                            this.$refs.upload.$refs.uploadRef.clearFiles();
                            this.open = false;
                            this.getPage();
                        });
                    }
                    else {
                        addDanger(this.form).then(response => {
                            this.msgSuccess("新增成功");
                            this.fileList = [];
                            this.$refs.upload.$refs.uploadRef.clearFiles();
                            this.open = false;
                            this.getPage();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$confirm('是否确认删除隐患上报"' + ids + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                let data;
                if (Array.isArray(ids)) {
                    data = ids;
                }
                else {
                    data = [ids];
                }
                return delDanger(data);
            }).then(() => {
                this.getPage();
                this.msgSuccess("删除成功");
            });
        },
    },
    components: { SubmitHistoryForm }
};
</script>
<style lang="scss" scoped>
  ::v-deep .el-dialog .el-dialog__body{
    margin-bottom:60px !important;
  }
</style>